package com.byb.server.web.rest;

import com.byb.server.web.rest.vm.ExpertOptionsVM;
import com.codahale.metrics.annotation.Timed;
import com.byb.server.service.ExpertOpinionService;
import com.byb.server.web.rest.util.HeaderUtil;
import com.byb.server.web.rest.util.PaginationUtil;
import com.byb.server.service.dto.ExpertOpinionDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing ExpertOpinion.
 */
@RestController
@RequestMapping("/api")
public class ExpertOpinionResource {

    private final Logger log = LoggerFactory.getLogger(ExpertOpinionResource.class);

    private static final String ENTITY_NAME = "expertOpinion";

    private final ExpertOpinionService expertOpinionService;

    public ExpertOpinionResource(ExpertOpinionService expertOpinionService) {
        this.expertOpinionService = expertOpinionService;
    }

    /**
     * POST  /expert-opinions : Create a new expertOpinion.
     *
     * @param expertOpinionDTO the expertOpinionDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new expertOpinionDTO, or with status 400 (Bad Request) if the expertOpinion has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/expert-opinions")
    @Timed
    public ResponseEntity<ExpertOpinionDTO> createExpertOpinion(@RequestBody ExpertOpinionDTO expertOpinionDTO) throws URISyntaxException {
        log.debug("REST request to save ExpertOpinion : {}", expertOpinionDTO);
        if (expertOpinionDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new expertOpinion cannot already have an ID")).body(null);
        }
        ExpertOpinionDTO result = expertOpinionService.save(expertOpinionDTO);
        return ResponseEntity.created(new URI("/api/expert-opinions/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /expert-opinions : Updates an existing expertOpinion.
     *
     * @param expertOpinionDTO the expertOpinionDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated expertOpinionDTO,
     * or with status 400 (Bad Request) if the expertOpinionDTO is not valid,
     * or with status 500 (Internal Server Error) if the expertOpinionDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/expert-opinions")
    @Timed
    public ResponseEntity<ExpertOpinionDTO> updateExpertOpinion(@RequestBody ExpertOpinionDTO expertOpinionDTO) throws URISyntaxException {
        log.debug("REST request to update ExpertOpinion : {}", expertOpinionDTO);
        if (expertOpinionDTO.getId() == null) {
            return createExpertOpinion(expertOpinionDTO);
        }
        ExpertOpinionDTO result = expertOpinionService.save(expertOpinionDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, expertOpinionDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /expert-opinions : get all the expertOpinions.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of expertOpinions in body
     */
    @GetMapping("/expert-opinions")
    @Timed
    public ResponseEntity<List<ExpertOpinionDTO>> getAllExpertOpinions(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of ExpertOpinions");
        Page<ExpertOpinionDTO> page = expertOpinionService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/expert-opinions");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /expert-opinions/:id : get the "id" expertOpinion.
     *
     * @param id the id of the expertOpinionDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the expertOpinionDTO, or with status 404 (Not Found)
     */
    @GetMapping("/expert-opinions/{id}")
    @Timed
    public ResponseEntity<ExpertOpinionDTO> getExpertOpinion(@PathVariable Long id) {
        log.debug("REST request to get ExpertOpinion : {}", id);
        ExpertOpinionDTO expertOpinionDTO = expertOpinionService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(expertOpinionDTO));
    }

    /**
     * DELETE  /expert-opinions/:id : delete the "id" expertOpinion.
     *
     * @param id the id of the expertOpinionDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/expert-opinions/{id}")
    @Timed
    public ResponseEntity<Void> deleteExpertOpinion(@PathVariable Long id) {
        log.debug("REST request to delete ExpertOpinion : {}", id);
        expertOpinionService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/expert-opinions?query=:query : search for the expertOpinion corresponding
     * to the query.
     *
     * @param query the query of the expertOpinion search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/expert-opinions")
    @Timed
    public ResponseEntity<List<ExpertOpinionDTO>> searchExpertOpinions(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of ExpertOpinions for query {}", query);
        Page<ExpertOpinionDTO> page = expertOpinionService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/expert-opinions");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    //expert-opinions_by_productId/{id}

    /**
     *
     * @param id
     * @param pageable
     * @return
     */
    @GetMapping("expert-opinions_by_productId/{id}")
    @Timed
    public ResponseEntity<ExpertOptionsVM> getAllExpertOpinionsByProductId(@PathVariable Long id, @ApiParam Pageable pageable) {
        log.debug("REST request to get a page of ExpertOpinions by ProductId");
        Page<ExpertOpinionDTO> page = expertOpinionService.findAllByProductId(id,pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "expert-opinions_by_productId/{id}");
        return new ResponseEntity<>(new ExpertOptionsVM(page.getTotalElements(),0,page.getContent()), headers, HttpStatus.OK);
    }
}
